package cn.cloudtogo.server.atomapi;

import cn.cloudtogo.common.GendbException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @author yaolianhua789@gmail.com
 **/
@Component
@Slf4j
public class ApiTokenObjectConverterHelper {

    private final ObjectMapper objectMapper;

    public ApiTokenObjectConverterHelper(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    public <T> String write(T data) {
        try {
            return objectMapper.writeValueAsString(data);
        } catch (JsonProcessingException e) {
            log.error("Write json value error. {}", e.getMessage(), e);
            throw new GendbException(String.format("Write json value error '%s'", e.getMessage()));
        }
    }

    public <T> T read(Class<T> clazz, String json) {
        try {
            return objectMapper.readValue(json, clazz);

        } catch (JsonProcessingException e) {
            log.error("Read json value error. {}", e.getMessage(), e);
            throw new GendbException(String.format("Read json value error '%s'", e.getMessage()));
        }
    }

}
